import Vue from 'vue'
import { getInnerOnePackProjectId } from '@/api/project'
import { getMenuProjectList } from '@/api/menu'

const state = {
  projectStatus: {},
  buildStepProgress: {},
  dynamicMenus: [],
  compTagList: [], // 组件标签信息
  detailConfigs: {}, // 组件构建时通过详情配置的数据，用来构建使用
  innerProjectId: '', // 内置项目ID
  buildStep: {} // 项目组件当前构建状态
}

const mutations = {
  SET_PROJECT_STATUS(state, value) {
    state.projectStatus = value
  },
  SET_BUILD_STEP_PROGRESS(state, value) {
    state.buildStepProgress = value
  },
  SET_DYNAMIC_MENUS(state, value) {
    state.dynamicMenus = value
  },
  SET_COMP_TAG_LIST(state, value) {
    if (state.compTagList.length > 0) {
      const el = state.compTagList.find(item => item.componentId === value.componentId)
      if (!el) {
        state.compTagList.push(value)
      }
    } else {
      state.compTagList.push(value)
    }
  },
  SET_DETAIL_CONFIG(state, cfg) {
    const compId = cfg.componentId
    const stateConfig = state.detailConfigs[compId] || {}
    const cfgUpEnvIds = cfg['upgradeEnvIds']
    const cfgSqlList = cfg['sqlList']
    const cfgStepOrders = cfg['stepOrders']
    if (cfgStepOrders && cfgStepOrders.length > 0) {
      stateConfig.stepOrders = cfgStepOrders
    }
    if (cfgSqlList && cfgSqlList.length > 0) {
      stateConfig.sqlList = cfgSqlList
    }
    if (cfgUpEnvIds && cfgUpEnvIds.length > 0) {
      stateConfig.upgradeEnvIds = cfgUpEnvIds
    }
    Vue.set(state.detailConfigs, compId, stateConfig)
  },
  SET_INNER_PROJECT_ID(state, value) {
    state.innerProjectId = value
  },
  SET_BUILD_STEP(state, value) {
    const valueCompId = value['componentId']
    const valueStep = value['stateStep']
    Vue.set(state.buildStep, valueCompId, valueStep)
  }
}

const actions = {
  changeDynamicMenus({ commit }) {
    return new Promise((resolve, reject) => {
      getMenuProjectList({}).then(response => {
        const { data } = response
        const projectRoutes = data.map(item => ({
          path: item.projectRootDir,
          name: item.projectRootDir,
          component: () => import('@/views/projectManage/projectList/index.vue'),
          meta: { title: item.projectName, icon: 'sub-project', projectId: item.projectId },
          children: []
        }))
        commit('SET_DYNAMIC_MENUS', projectRoutes)
        localStorage.setItem('dynamicRoutes', JSON.stringify(projectRoutes))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  changeInnerProjectId({ commit }) {
    return new Promise((resolve, reject) => {
      if (state.innerProjectId) {
        resolve(state.innerProjectId)
        return
      }
      getInnerOnePackProjectId().then(res => {
        commit('SET_INNER_PROJECT_ID', res.data)
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
